package com.ejlchina.tool.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.adolf.androiddemo.databinding.ItemLightTimeBinding
import com.ejlchina.tool.bean.LightTimeBean

class LightTimeAdapter(private val dataList: MutableList<LightTimeBean>,private val startTimeClick: (Int) -> Unit,
                       private val endTimeClick: (Int) -> Unit,
                       private val removeClick: (Int) -> Unit
) : RecyclerView.Adapter<LightTimeAdapter.LightTimeViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LightTimeViewHolder {
        val binding = ItemLightTimeBinding.inflate(LayoutInflater.from(parent.context),parent,false)
        return LightTimeViewHolder(binding,startTimeClick,endTimeClick,removeClick)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onBindViewHolder(holder: LightTimeViewHolder, position: Int) {
        holder.bindData(dataList[position],position)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun addLightTime(){
        val timeBean = LightTimeBean()
        dataList.add(timeBean)
        notifyDataSetChanged()
    }

    inner class LightTimeViewHolder(
        private val binding: ItemLightTimeBinding,
        private val startTimeClick: (Int) -> Unit,
        private val endTimeClick: (Int) -> Unit,
        private val removeClick:(Int) -> Unit
    ) : RecyclerView.ViewHolder(binding.root) {
        @SuppressLint("SetTextI18n")
        fun bindData(data: LightTimeBean, position: Int) {
            binding.tvStateTime.text = "${formatTime(data.startTime.hour)}:${formatTime(data.startTime.minute)}"
            binding.tvEndTime.text = "${formatTime(data.endTime.hour)}:${formatTime(data.endTime.minute)}"
            binding.tvStateTime.setOnClickListener {
                startTimeClick(position)
            }
            binding.tvEndTime.setOnClickListener {
                endTimeClick(position)
            }
            binding.ivRemove.setOnClickListener {
                removeClick(position)
                notifyDataSetChanged()
            }
        }

        private fun formatTime(hourMinute: Int): String{
            return hourMinute.toString().padStart(2,'0')
        }
    }
}

